﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using BSDS.Core.Infrastructure.Logging;
using BSDS.Core.Model.Conversion.Configuration;
using BSDS.Core.Model.Data;

namespace BSDS.Core.Model.Conversion.Processing
{
    public static class InsertColumnsProcessor
    {
        private static InsertColumnsConfiguration _insertConfiguration;

        public static void LoadConfiguration(string configFile)
        {
            XmlSerializer sr = new XmlSerializer(typeof(InsertColumnsConfiguration));

            if (File.Exists(configFile))
            {
                using (var f = new FileStream(configFile, FileMode.Open))
                {
                    if (f != null)
                    {
                        _insertConfiguration = sr.Deserialize(f) as InsertColumnsConfiguration;
                    }
                }
            }
            else
            {
                throw new FileNotFoundException("Unable to open the Insert columns configuration file: " + configFile);
            }
        }

        public static void SaveConfiguration(string configFile)
        {
            XmlSerializer sr = new XmlSerializer(typeof(InsertColumnsConfiguration));

            using (var tr = new StreamWriter(configFile))
            {
                sr.Serialize(tr, _insertConfiguration);
            }
        }

        public static void InsertColumns(this BsdsData data)
        {
            foreach (var entity in data.Entities)
            {
                foreach (var c in _insertConfiguration.Columns)
                {
                    entity.AppendAttributeValue(new AttributeValue(new AttributeInfo(c.name, c.type, false), c.value));
                }
            }
        }

        public static void CreateSampleData()
        {
            _insertConfiguration = new InsertColumnsConfiguration();
            _insertConfiguration.Columns = new Column[] 
            { 
                new Column() { name = "NewColumn1", type = "String", value = "myValue1" },
                new Column() { name = "NewColumn2", type = "Double", value = "1.000000" },
                new Column() { name = "NewColumn3", type = "Boolean", value = "true" },
            };

            SaveConfiguration("SampleInsertColumnsConfiguration.xml");
        }
    }
}
